package com.baizan.daka.net;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializer;

import java.util.Date;

/**
 * Created by DemoJameson on 2016/7/21.
 */
public class GsonManager {
  private static Gson gson = getGson();

  private GsonManager() {
  }

  public static Gson getGson() {
    if (gson == null) {
      gson = new GsonBuilder().registerTypeAdapter(int.class,
          (JsonDeserializer<Integer>) (json, typeOfT, context) -> {
            try {
              return json.getAsInt();
            } catch (NumberFormatException e) {
              return 0;
            }
          })
          .registerTypeAdapter(long.class, (JsonDeserializer<Long>) (json, typeOfT, context) -> {
            try {
              return json.getAsLong();
            } catch (NumberFormatException e) {
              return 0L;
            }
          })
          .registerTypeAdapter(float.class, (JsonDeserializer<Float>) (json, typeOfT, context) -> {
            try {
              return json.getAsFloat();
            } catch (NumberFormatException e) {
              return 0f;
            }
          })
          .registerTypeAdapter(double.class,
              (JsonDeserializer<Double>) (json, typeOfT, context) -> {
                try {
                  return json.getAsDouble();
                } catch (NumberFormatException e) {
                  return 0d;
                }
              })
          .registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> {
            try {
              return new Date(json.getAsJsonPrimitive().getAsLong());
            } catch (NumberFormatException e) {
              return new Date();
            }
          })
          .registerTypeAdapter(boolean.class,
              (JsonDeserializer<Boolean>) (json, typeOfT, context) -> {
                try {
                  String booleanStr = json.getAsString();
                  if ("1".equals(booleanStr)) {
                    return true;
                  } else if ("0".equals(booleanStr)) {
                    return false;
                  }
                  return json.getAsJsonPrimitive().getAsBoolean();
                } catch (Exception e) {
                  return false;
                }
              })
          .create();
    }
    return gson;
  }
}
